# -*- coding: UTF-8 -*-
import pymongo
import redis
from threading import Lock, Thread
import asyncio
import websockets
from okex.ws_server import WsServer
from okex.web_server import WebServer
from okex.ok_client import OKEXWebsocket
import threading

class OKRobot:
    def __init__(self,rest_host=None,ws_host=None,rest_timeout=5,ws_ping_interval=20,
    redis_server='127.0.0.1',redis_port=6380,redis_pass=None,redis_db=0,
    mongo_server='127.0.0.1',mongo_port=27018,mongo_user=None,mongo_pass=None,logger=None):
        #初始化
        self.rest_host = rest_host
        self.ws_host = ws_host
        self.rest_timeout = rest_timeout
        self.ws_ping_interval = ws_ping_interval
        self.logger = logger
        # 需要的监听服务 1 ok ws 监听服务 2 启动rest server 3 启动ws server

        # mongo 客户端
        self.mongo_client = pymongo.MongoClient(host=mongo_server, port=mongo_port,username=mongo_user,password=mongo_pass)
        self.mongo_client_query = pymongo.MongoClient(host=mongo_server, port=mongo_port,username=mongo_user,password=mongo_pass)
        # redis 客户端
        redis_pool = redis.ConnectionPool(host=redis_server, port=redis_port, db=redis_db,password=redis_pass)
        re = redis.Redis(connection_pool=redis_pool)
        self.redis_client = re

        self.wsServer = None
        self.webServer = None
        self.okClient = None
        self.okex_ws = None
        self.tasks = []

    def start(self):
        """
        启动客户端，客户端连接成功后，会调用 on_open这个方法
        on_open 方法调用后，才可以向服务器发送消息的方法.
        """
        self.logger.info("start _run_ws_server")
        self._run_ws_server()
  
        self.logger.info("start _run_ok_ws_server")
        self._run_ok_ws_server()
        
        self.logger.info("start _run_web_server")
        self._run_web_server()

    def stop(self):
        pass
    def _run_ws_server(self):
        self.wsServer = WsServer(logger=self.logger,mongo_client=self.mongo_client_query)
        new_loop = asyncio.new_event_loop()
        try:
            asyncio.set_event_loop(new_loop)
            task = asyncio.ensure_future(self.wsServer.run())
            new_loop.run_until_complete(asyncio.wait([task]))
        except:
           new_loop.close() 

    def _run_web_server(self):
        self.webServer = WebServer(logger=self.logger,redis_client=self.redis_client, mongo_client=self.mongo_client_query)
        # new_loop = asyncio.new_event_loop()
        try:
            # asyncio.set_event_loop(new_loop)
            # new_loop.run_until_complete(self.webServer.run())
            # new_loop.run_forever()
            self.webServer.run()
        except Exception as e:
            # new_loop.close()
            print(e)
            self.logger.info("web error")
            pass


    def _run_ok_ws_server(self):
        self.okex_ws = OKEXWebsocket(host=self.ws_host, ping_interval=self.ws_ping_interval,
            logger=self.logger,redis_client=self.redis_client,
            mongo_client=self.mongo_client,msg_callback=self.wsServer.msg_response)
        self.okex_ws.start()


